package com.example.finger.dialog;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.finger.FingerHelper;
import com.example.finger.R;
import com.example.finger.bean.SoketOrder;
import com.example.finger.socket.SoketUploadData;
import com.example.finger.rules.FingerLib;
import com.example.finger.util.MatchFinger;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lyxmaster.lib.toasty.Toasty;
import com.lyxmaster.lib.util.DataConfig;
import com.lyxmaster.lib.view.BaseActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by LYX on 2018/11/21.
 */

public class DownLoadDialog extends BaseDialog {
    public TextView textViewTip;
    public TextView textViewTitle;
    private FingerLib m_szHost = FingerHelper.getInStance().m_szHost;
    private Context context;

    private int order = 0;
    private final int CLEANFINGER = 1;
    private final int INPUTMANAGER = 2;
    private final int EQUESEFINGER = 3;
    private int fingerIndex = 0;

    private List<String> FingerData = new ArrayList<>();


    @Override
    public View createView(Context context, LayoutInflater inflater, ViewGroup container) {
        super.createView(context,inflater,container);
        this.context = context;
        return inflater.inflate(R.layout.dialog_download_task, container, false);
    }

    public static DownLoadDialog getInstance(String title) {
        DownLoadDialog dialogFragment = new DownLoadDialog();
        dialogFragment.setCanceledBack(false);
        dialogFragment.setCanceledOnTouchOutside(false);

        Bundle args = new Bundle();
        args.putString("title", title);
        dialogFragment.setArguments(args);

        return dialogFragment;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        FingerData = new Gson().fromJson(getArguments().getString("title"), new TypeToken<List<String>>(){}.getType());

        textViewTip = getView().findViewById(R.id.tv_tip);
        textViewTitle = getView().findViewById(R.id.tv_title);
        textViewTitle.setText("数据同步");
        textViewTip.setText("正在初始化");

        order = CLEANFINGER;

        m_szHost.setOnFingerDoneListener(new FingerLib.OnFingerDoneListener() {
            @Override
            public void OnGetMessage(String content) {
                switch (order){
                    case CLEANFINGER:
//                        downLoadManageFInger();
                        order = EQUESEFINGER;
                        textViewTip.setText("请按下管理员指纹");
                        m_szHost.Run_CmdGetFeatureOfCapturedFP();
                        break;
                    case EQUESEFINGER:
                        if(content.startsWith("0")){
                            for(int i=0; i<FingerData.size(); i++){
                                DataConfig.hexStringToHexBytes(FingerData.get(i));
                                if(MatchFinger.match(DataConfig.hexStringToHexBytes(FingerData.get(i)), m_szHost.m_TemplateData)){
                                    Toasty.success(context, "匹配成功").show();
                                    textViewTip.setText("正在验证数据，请勿断开设备");
                                    SoketOrder soketOrder = new SoketOrder();
                                    soketOrder.setResult(SoketOrder.DOWNLOADTASK);
                                    SoketUploadData.upload(new Gson().toJson(soketOrder).getBytes());
                                    return;
                                }
                            }
                            new Timer().schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    ((Activity)(context)).runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            order = EQUESEFINGER;
                                            textViewTip.setText("请按下管理员指纹");
                                            m_szHost.Run_CmdGetFeatureOfCapturedFP();
                                            Toasty.error(context, "匹配失败").show();
                                        }
                                    });
                                }
                            }, 1000);

                        }else {
                            new Timer().schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    ((Activity)(context)).runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            textViewTip.setText("获取失败,请再按一次");
                                            order = EQUESEFINGER;
                                            m_szHost.Run_CmdGetFeatureOfCapturedFP();
                                        }
                                    });
                                }
                            }, 1000);
                        }
                        break;
                }
            }
        });

        m_szHost.Run_CmdDeleteAll();
    }

    private void downLoadManageFInger(){
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                ((Activity)(context)).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        fingerIndex++;
                        order = INPUTMANAGER;
                        FingerHelper.getInStance().m_szHost.m_TemplateData = DataConfig.hexStringToHexBytes(FingerData.get(fingerIndex-1));
                        FingerHelper.getInStance().m_szHost.m_nTemplateSize = 570;
                        FingerHelper.getInStance().m_szHost.Run_CmdWriteTemplate(FingerHelper.getInStance().ManageFIngerID+fingerIndex-1);
                    }
                });
            }
        }, 200);
    }

    public void downLoad(){
        textViewTip.setText("下载成功，正在重启应用");
        Toasty.success(context, "下载成功，正在重启应用").show();
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                ((Activity)(context)).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismiss();
                        Intent intent = context.getPackageManager()
                                .getLaunchIntentForPackage(((Activity)(context)).getApplication().getPackageName());
                        PendingIntent restartIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
                        AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
                        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重启应用
                        System.exit(0);
                    }
                });
            }
        },1500);
    }

//    @Override
//    public void onDestroy(){
//        super.onDestroy();
//        m_szHost.setOnFingerListener(null);
//        m_szHost.setOnFingerDoneListener(null);
//        try{
//            m_szHost.Run_CmdCancel();
//        }catch(Exception e) {}
//    }

    @Override
    public void dismiss(){
        bShow = false;
        ((BaseActivity)(context)).hud.show("正在退出操作");
        m_szHost.setOnFingerListener(null);
        m_szHost.setOnFingerDoneListener(null);
//        m_szHost.setOnFingerDoneListener(new FingerLib.OnFingerDoneListener() {
//            @Override
//            public void OnGetMessage(String content) {
//                ((BaseActivity) (context)).hud.dismiss();
//                m_szHost.setOnFingerDoneListener(null);
//                DownLoadDialog.super.dismiss();
//            }
//        });
        m_szHost.Run_CmdCancel();
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                ((Activity)(getContext())).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ((BaseActivity) (context)).hud.dismiss();
                        DownLoadDialog.super.dismiss();
                    }
                });
            }
        },2000);
    }
}
